package com.spring.cloud.study.gateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/3/2
 * Time: 14:13
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Component
public class AccessFilter extends ZuulFilter{



    private Logger log = LoggerFactory.getLogger(AccessFilter.class);

    @Override
    public String filterType() {
        return "post";
    }
    @Override
    public int filterOrder() {
        return 0;
    }
    @Override
    public boolean shouldFilter() {

        return true;
    }

    /**
     * 过滤客户请求token是否存在
     * @return
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set("startTime", System.currentTimeMillis());

      //  Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
     //   System.out.println(authentication.getPrincipal().toString());

      /*  if (authentication != null) {
            RequestContext requestContext = RequestContext.getCurrentContext();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

            requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
            requestContext.addZuulRequestHeader(SecurityConstants.ROLE_HEADER,  CollectionUtil.join(authentication.getAuthorities(),","));

        }*/
      /*  RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        String access_token = request.getParameter("access_token");
        HttpServletResponse response = ctx.getResponse();
        if(!requestURI.matches("^/\\w*//*oauth/token\\*//*\\w*") && !requestURI.matches("^/\\w*//*oauth/authorize\\*//*\\w*")){
            if(access_token == null || access_token.equals("")){

                response.setContentType("application/json; charset=utf-8");
                response.setCharacterEncoding("utf-8");

                ctx.setSendZuulResponse(false);
                ctx.setResponseStatusCode(500);
                JSONObject  jsonObject = new JSONObject();
                jsonObject.put("code",500);
                jsonObject.put("msg","access_token不能为空");
                ctx.setResponse(response);
                ctx.setResponseBody(jsonObject.toString());
            }
        }*/

        return null;
    }


}
